package com.daka.controller;

import com.daka.annotation.Login;
import com.daka.entity.Organization;
import com.daka.entity.User;
import com.daka.enumerate.StatusCode;
import com.daka.service.UserService;
import com.daka.tools.MD5Util;
import com.daka.vo.request.ResetPasswordVo;
import com.daka.vo.request.UserPageRequestVo;
import com.daka.vo.response.BaseResponseVo;
import com.daka.vo.response.DataResponseVo;
import com.daka.vo.response.ListDataResponseVo;
import com.daka.vo.response.PageListResponse;
import com.daka.vo.response.user.UserDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;


/**
 * @author beliveli on 2016/3/31 0031.
 */
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource(name = "userService")
    private UserService userService;

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/listByOrgId", consumes = "application/json")
    @Login
    public ListDataResponseVo listByOrgId(HttpSession session, @Valid @RequestBody Organization organization) {

        int orgId;
        if (organization.getOrgId() == 0) {
            orgId = Integer.parseInt(session.getAttribute("orgId").toString());
        } else {
            orgId = organization.getOrgId();
        }

        List<User> userList = userService.selectByOrgId(orgId);
        return new ListDataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), userList);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/pageListByOrgId", consumes = "application/json")
    @Login
    public DataResponseVo<PageListResponse<User>> pageListByOrgId(HttpSession session, @Valid @RequestBody UserPageRequestVo userPageRequestVo) {

        int orgId;
        if (null == userPageRequestVo.getOrgId() || userPageRequestVo.getOrgId() == 0) {
            orgId = Integer.parseInt(session.getAttribute("orgId").toString());
        } else {
            orgId = userPageRequestVo.getOrgId();
        }

        List<User> userList = userService.selectPageByOrgId(orgId, userPageRequestVo.getUserName(), (userPageRequestVo.getPageIndex() - 1) * userPageRequestVo.getPageSize(), userPageRequestVo.getPageSize());
        int count = userService.selectCountByOrgId(orgId, userPageRequestVo.getUserName());
        PageListResponse<User> page = new PageListResponse<>(userList, count);
        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), page);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/list", consumes = "application/json")
    @Login
    public ListDataResponseVo list() {
        List<User> userList = userService.selectAll();
        return new ListDataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), userList);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/login", consumes = "application/json")
    public DataResponseVo<UserDetailVo> login(@Valid @RequestBody User userParam, HttpSession session) {
        DataResponseVo<UserDetailVo> result = userService.login(userParam);
        if (result != null && result.getStatusCode() == StatusCode.SUCCESS.getStatusCode()) {
            session.setAttribute("userId", result.getData().getUserId());
            session.setAttribute("orgId", result.getData().getOrgId());
//            session.setAttribute("org", result.getData().getOrganization());
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/invalidOrg", consumes = "application/json")
    public DataResponseVo<User> invalidOrg(@Valid @RequestBody User userParam) {

        User user = userService.updateOrgIdById(userParam.getOrgId(), userParam.getUserId());

        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), user);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/sendCode", consumes = "application/json")
    public BaseResponseVo sendCode(@Valid @RequestBody ResetPasswordVo resetPasswordVo) {

        User user = userService.selectByPhone(resetPasswordVo.getPhone());
        if (user == null) {
            return new BaseResponseVo(StatusCode.SELECT_ITEM_NOT_EXISTS.getStatusCode(), StatusCode.SELECT_ITEM_NOT_EXISTS.getStatusMessage());
        }
        String code = userService.sendVerifierCode(resetPasswordVo.getPhone());
        if (code.length() > 0) {
            return new BaseResponseVo(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage());
        }
        return new BaseResponseVo(StatusCode.SEND_CODE_ERROR.getStatusCode(), StatusCode.SEND_CODE_ERROR.getStatusMessage());
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/resetPassword", consumes = "application/json")
    public BaseResponseVo resetPassword(@Valid @RequestBody ResetPasswordVo resetPasswordVo) {

        boolean flag = userService.checkVerifierCode(resetPasswordVo.getPhone(), resetPasswordVo.getCode());
        if (flag) {
            User user = userService.selectByPhone(resetPasswordVo.getPhone());
            user.setPassword(MD5Util.MD5(resetPasswordVo.getPassword()));
            int resultCount = userService.updatePasswordById(user);
            if (resultCount == 0) {
                return new BaseResponseVo(StatusCode.ADD_ERROR.getStatusCode(), StatusCode.ADD_ERROR.getStatusMessage());
            }
            return new BaseResponseVo(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage());
        }
        return new BaseResponseVo(StatusCode.RESET_ERROR.getStatusCode(), StatusCode.RESET_ERROR.getStatusMessage());
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/updatePassword", consumes = "application/json")
    @Login
    public DataResponseVo<String> updatePassword(@Valid @RequestBody User userParam, HttpSession session) {

        int userId = Integer.parseInt(session.getAttribute("userId").toString());

        User user = userService.selectById(userId);
        user.setPassword(MD5Util.MD5(userParam.getPassword()));
        int resultCount = userService.updatePasswordById(user);
        if (resultCount == 0) {
            return new DataResponseVo<>(StatusCode.ADD_ERROR.getStatusCode(), StatusCode.ADD_ERROR.getStatusMessage());
        }
        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage());
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/checkPassword", consumes = "application/json")
    @Login
    public BaseResponseVo checkPassword(@Valid @RequestBody User userParam, HttpSession session) {

        int userId = Integer.parseInt(session.getAttribute("userId").toString());

        User user = userService.selectById(userId);
        if (user.getPassword().equals(MD5Util.MD5(userParam.getPassword()))) {
            return new BaseResponseVo(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage());
        } else {
            return new BaseResponseVo(StatusCode.JAVA_THROW_EXCEPTION.getStatusCode(), StatusCode.JAVA_THROW_EXCEPTION.getStatusMessage());
        }

    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/checkLogin", consumes = "application/json")
    public BaseResponseVo checkLogin(HttpSession session) {
        if (session.getAttribute("userId") == null) {
            return new BaseResponseVo(StatusCode.NOT_LOGIN.getStatusCode(), StatusCode.NOT_LOGIN.getStatusMessage());
        }
        return new BaseResponseVo(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage());
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/updateStatus", consumes = "application/json")
    @Login
    public DataResponseVo<User> updateStatus(@Valid @RequestBody User user) {

        User result = userService.updateStatus(user.getUserId());

        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), result);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/info", consumes = "application/json")
    @Login
    public DataResponseVo<User> info(@Valid @RequestBody User user) {

        User result = userService.selectById(user.getUserId());

        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), result);
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/save", consumes = "application/json")
    @Login
    public DataResponseVo<User> save(@Valid @RequestBody User user) {

        User checkExists = userService.selectByPhone(user.getPhone());
        /*
            新建    已存在    /                               报错
            新建    不存在    /                               正常
            修改    不存在    /                               正常
            修改    已存在    已存在userId = 当前保存UserId   正常
            修改    已存在    已存在userId != 当前保存UserId  报错
         */
        if ((checkExists != null && user.getUserId() == 0) || (user.getUserId() != 0 && checkExists != null && user.getUserId() != checkExists.getUserId())) {
            return new DataResponseVo<>(StatusCode.ADD_ERROR.getStatusCode(), "手机号已存在");
        }

        User result = userService.save(user);
        if (result == null) {
            return new DataResponseVo<>(StatusCode.ADD_ERROR.getStatusCode(), "服务器异常，请联系系统管理员");
        }

        return new DataResponseVo<>(StatusCode.SUCCESS.getStatusCode(), StatusCode.SUCCESS.getStatusMessage(), result);
    }
}
